package com.ruoyi.system.task;

import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.QywxUtil;
import com.ruoyi.common.utils.sign.AESUtils;
import com.ruoyi.common.utils.vo.DeptUserVO;
import com.ruoyi.common.utils.vo.DeptVO;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;

@Component
@RequiredArgsConstructor
public class SyncWxTask {

    private final ISysDeptService sysDeptService;

    private final ISysUserService sysUserService;

    @Scheduled(cron = "0 0 5 * * ?")
//    @PostConstruct
    public void SyncTask(){
        SyncDept();
        SyncUser();
    }

    private void SyncDept(){
        String token = QywxUtil.getToken();
        List<DeptVO> deptList = QywxUtil.getDeptList(token);
        deptList.forEach(m->{
            SysDept sysDept = sysDeptService.selectDeptById(m.getId());
            if (sysDept == null){
                sysDept = new SysDept();
                sysDept.setStatus("0");
                sysDept.setDeptId(m.getId());
                sysDept.setDeptName(m.getName());
                sysDept.setParentId(m.getParentId());
                sysDeptService.insert(sysDept);
            }
        });
    }

    private void SyncUser(){
        String token = QywxUtil.getToken();
        List<SysDept> deptList = sysDeptService.selectList(new SysDept());
        deptList.forEach(m->{
            List<DeptUserVO> userList = QywxUtil.getDeptUserList(token, m.getDeptId().toString());
            userList.forEach(n->{
                SysUser user = sysUserService.selectUserByCode(n.getUserId());
                if (user == null){
                    user = new SysUser();
                    user.setCode(n.getUserId());
                    user.setUserName(n.getUserId());
                    user.setNickName(n.getName());
                    user.setSex(n.getGender()== "1" ? "0" : (n.getGender() == "2" ? "1" : "2" ));
                    user.setPhonenumber(n.getMobile());
                    user.setAvatar(n.getAvatar());
                    user.setDeptId(n.getDepartmentId());
                    user.setDuties(n.getPosition());
                    sysUserService.insertUser(user);
                }
            });
        });
    }




}
